# coding: utf-8 
from __future__ import print_function, unicode_literals
from PyInquirer import prompt, print_json
from sys import argv
import json
import os
import argparse

_mac_config = {
    "location": "/usr/local/etc/shadowsocks-libev.json",
    "_local_port": 1086
}

_linux_config = {
    "location": "/etc/shadowsocks-libev/config.json",
    "_local_port": 1080
}

relative_path = ['..', '..', '..', '..', 'local', 'ss', 'location.json']
location_json_path = os.path.abspath(os.path.join(__file__, *relative_path))

def load_file(filename):
    with open(filename) as fp:
        json_dict = json.load(fp)
    return json_dict['configs']


def make_inquirer(configs):
    choices = [c['remarks'] for c in configs]
    questions = [{
        'type': 'list',
        'name': 'node',
        'message': 'select node:',
        'choices': choices 
    }]
    answers = prompt(questions)
    for c in configs:
        if answers['node'] == c['remarks']:
            return c
    return None


def send2file(ss_config, local_config):
    if not os.path.exists(local_config['location']):
        local_config['location'] = str(input("Config File not exists, Please enter file path to write in:\n> "))
    template = """{{
  "server": "{server}",
  "server_port": {server_port},
  "local_port": {_local_port},
  "password": "{password}",
  "method": "{method}",
  "plugin": "",
  "plugin_opts": "",
  "plugin_args": "",
  "remarks": "{remarks}",
  "timeout": 60
}}"""
    file_content = template.format(**ss_config, **local_config)
    print(local_config['location'])
    with open(local_config['location'], 'wb') as fconfig:
        fconfig.write(file_content.encode('utf-8'))
    return file_content


def read_location(location_path=location_json_path):
    with open(location_path) as fp:
        return json.load(fp)


def write_location(local_cfg, location_path=location_json_path):
    with open(location_path, 'w')  as fp:
        json.dump(local_cfg, fp)


if __name__ == '__main__':
    parser =  argparse.ArgumentParser(description='为`shadowsocks-libev`选择ss代理。选择ss配置文件，输出配置。')
    parser.add_argument('json_path', type=str,
                        help='location of configuration json file')
    parser.add_argument('-m', '--mac', action='store_true', dest='mac', default=None,
                        help='use in mac host')
    parser.add_argument('-l', '--linux', action='store_false', dest='mac',
                        help='use in linux host')
    parser.add_argument('-p', '--port', metavar='number', type=int, dest='port',
                        help='the port number')
    parser.add_argument('-o', '--output', metavar='str', type=str, dest='output',
                        help='output config path')
    parser.add_argument('-s', '--save', default=False, action='store_true', 
                        help='save config path.')

    args = parser.parse_args()

    if args.mac is not None:
        config = _mac_config if args.mac else _linux_config
    else: 
        # load config from file
        config = read_location()
        if args.port is not None:
            config['_local_port'] = int(arg.port)
        if args.output is not None:
            config['location'] = args.output

    json_configs = load_file(args.json_path)
    selected = make_inquirer(json_configs)
    print(send2file(selected, config))

    if args.save:
        write_location(config)